<template>
  <el-dialog 
    :title="dialogTitle" 
    v-model="visible" 
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      :disabled="dialogType === 'view'"
    >
      <el-row :gutter="20">
        <!-- 第一行：登录账号、姓名 -->
        <el-col :span="12">
          <el-form-item label="登录账号" prop="user">
            <el-input 
              v-model="form.username" 
              placeholder="请输入登录账号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="Name">
            <el-input 
              v-model="form.realName" 
              placeholder="请输入姓名"
              clearable
            />
          </el-form-item>
        </el-col>
        
        <!-- 第二行：角色类型、角色名称 -->
        <el-col :span="12">
          <el-form-item label="角色类型" prop="jslx">
            <el-select 
              v-model="form.roleType" 
              placeholder="请选择角色类型"
              style="width: 100%"
              @change="handleRoleTypeChange"
              clearable
            >
              <el-option label="高级职业" value="system" />
              <el-option label="普通职业" value="non-system" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色名称" prop="lxName">
            <el-input 
              v-model="form.roleName" 
              placeholder="请输入角色名称"
              clearable
            />
          </el-form-item>
        </el-col>
        
        <!-- 第三行：出生日期、性别 -->
        <el-col :span="12">
          <el-form-item label="出生日期" prop="Date">
            <el-date-picker
              v-model="form.birthDate"
              type="datetime"
              placeholder="选择出生日期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        
        <!-- 第四行：状态、手机号 -->
        <el-col :span="12">
          <el-form-item label="状态" prop="zt">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input 
              v-model="form.phone" 
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>
        </el-col>
        
        <!-- 第五行：邮箱、组织机构 -->
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input 
              v-model="form.email" 
              placeholder="请输入邮箱地址"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织机构" prop="zzjg">
            <el-select 
              v-model="form.organization" 
              placeholder="请选择组织机构"
              style="width: 100%"
              clearable
            >
              <el-option label="大学" value="university" />
              <el-option label="中学" value="middle-school" />
              <el-option label="小学" value="primary-school" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 底部操作按钮 -->
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          v-if="dialogType !== 'view'"
        >
          提交
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserDialog',
  props: {
    visible: Boolean,
    dialogType: {
      type: String,
      default: 'add',
      validator: (value) => ['add', 'edit', 'view'].includes(value)
    },
    formData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:visible', 'submit'],
  setup(props, { emit }) {
    const formRef = ref()
    const visible = ref(false)

    // 表单数据
    const form = reactive({
      username: '',
      realName: '',
      roleType: '',
      roleName: '',
      birthDate: '',
      gender: 1,
      status: 1,
      phone: '',
      email: '',
      organization: ''
    })

    // 计算对话框标题
    const dialogTitle = computed(() => {
      const titles = {
        add: '新增用户',
        edit: '编辑用户',
        view: '查看用户'
      }
      return titles[props.dialogType] || '用户信息'
    })

    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入登录账号', trigger: ['blur', 'change'] },
        {
          pattern: /^[A-Za-z0-9`~!@#$%^&*()_\-+={}[\]|\\:;"'<>,.?/]*$/,
          message: '只能输入数字、英文和特殊字符，不能有空格',
          trigger: ['blur', 'change'],
        },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: ['blur', 'change'] }
      ],
      realName: [
        { required: true, message: '请输入姓名', trigger: ['blur', 'change'] },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: ['blur', 'change'] }
      ],
      roleType: [
        { required: true, message: '请选择角色类型', trigger: ['blur', 'change'] }
      ],
      roleName: [
        { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: ['blur', 'change'] }
      ],
      birthDate: [
        { required: true, message: '请选择出生日期', trigger: ['blur', 'change'] }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: ['blur', 'change'] }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: ['blur', 'change'] }
      ],
      phone: [
        {
          pattern: /^1[3-9]\d{9}$/,
          message: '请输入正确的手机号码',
          trigger: ['blur', 'change'],
        }
      ],
      email: [
        {
          pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
          message: '请输入正确的邮箱地址',
          trigger: ['blur', 'change'],
        }
      ]
    }

    // 监听visible属性变化
    watch(() => props.visible, (newVal) => {
      visible.value = newVal
      if (newVal) {
        // 对话框打开时，填充表单数据
        Object.assign(form, props.formData)
      } else {
        // 对话框关闭时，重置表单
        resetForm()
      }
    })

    // 监听内部visible变化，同步到父组件
    watch(visible, (newVal) => {
      emit('update:visible', newVal)
    })

    // 角色类型改变事件
    const handleRoleTypeChange = () => {
      form.roleName = '' // 清空角色名称
    }

    // 关闭对话框
    const handleClose = () => {
      visible.value = false
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        emit('submit', { ...form })
        handleClose()
      } catch (error) {
        ElMessage.error('表单验证失败，请检查输入内容')
      }
    }

    // 重置表单
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      Object.assign(form, {
        username: '',
        realName: '',
        roleType: '',
        roleName: '',
        birthDate: '',
        gender: 1,
        status: 1,
        phone: '',
        email: '',
        organization: ''
      })
    }

    return {
      formRef,
      visible,
      form,
      rules,
      dialogTitle,
      handleRoleTypeChange,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>